<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">博客管理系统</h2>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="100px">
        <el-form-item label="用户名或邮箱" prop="usernameOrEmail">
          <el-input v-model="loginForm.usernameOrEmail" placeholder="请输入用户名或邮箱"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
        </el-form-item>
        <!-- 显示错误信息 -->
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { authApi } from '@/api/authApi'
import { ElMessage } from 'element-plus'
import { loginFormRules } from '@/utils/formRules' // Import the rules

const loginFormRef = ref(null)
// Add form model
const loginForm = ref({
  usernameOrEmail: '',
  password: ''
})
const router = useRouter()
const username = ref('')
const password = ref('')
const errorMessage = ref('')
const loading = ref(false)

const handleLogin = async () => {

  // 验证表单
  if (!loginFormRef.value.validate()) return

  try {
    await loginFormRef.value.validate()

    loading.value = true
    errorMessage.value = ''
    
    // 使用authApi调用登录接口
    const response = await authApi.login({
      usernameOrEmail: loginForm.value.usernameOrEmail,
      password: loginForm.value.password
    })

    if (response.success) {
      // 存储登录状态和token
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('loginResponse', JSON.stringify(response))
      localStorage.setItem('token', response.data.accessToken)
      
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      errorMessage.value = response.data?.message || '登录失败'
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    errorMessage.value = error.response?.data?.message || '网络错误，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.login-btn {
  width: 100%;
}

.error-message {
  color: #f56c6c;
  text-align: center;
  margin-top: 10px;
}
</style>